from pypylon import pylon
import numpy

## basler ccd相机操作

#camera = pylon.InstantCamera(pylon.TlFactory.GetInstance().CreateFirstDevice())
#camera.Open()

## demonstrate some feature access
#new_width = camera.Width.GetValue() - camera.Width.GetInc()
#if new_width >= camera.Width.GetMin():
#    camera.Width.SetValue(new_width)

#numberOfImagesToGrab = 100
#camera.StartGrabbingMax(numberOfImagesToGrab)

#while camera.IsGrabbing():
#    grabResult = camera.RetrieveResult(5000, pylon.TimeoutHandling_ThrowException)

#    if grabResult.GrabSucceeded():
#        # Access the image data.
#        print("SizeX: ", grabResult.Width)
#        print("SizeY: ", grabResult.Height)
#        img = grabResult.Array
#        print("Gray value of first pixel: ", img[0, 0])

#    grabResult.Release()
#camera.Close()

## Modbsu_tk库使用execute(slave,功能代码,开始地址,quantity_of_x=0,output_value=0,data_format="",指定长度=-1)
import serial
import modbus_tk
import modbus_tk.defines as cst
from modbus_tk import modbus_rtu

def mod(PORT="com5"):
    read = []
    alarm = ""
    try:
        # 设定串口为从站
        master = modbus_rtu.RtuMaster(serial.Serial(port=PORT,baudrate=19200, bytesize=8, parity='N', stopbits=1))
        master.set_timeout(5.0)
        master.set_verbose(True)

        #READ_COILS = 1 读线圈
        #READ_DISCRETE_INPUTS = 2 读离散输入
        #READ_HOLDING_REGISTERS = 3  【读保持寄存器】
        #READ_INPUT_REGISTERS = 4  读输入寄存器
        #WRITE_SINGLE_COIL = 5  写单一线圈
        #WRITE_SINGLE_REGISTER = 6  写单一寄存器
        #WRITE_MULTIPLE_COILS = 15 写多个线圈 【强制多点线圈】
        #WRITE_MULTIPLE_REGISTERS = 16  写多寄存器 【写乘法寄存器】
        #举例：
        #logger.info(master.execute(1, cst.READ_COILS, 0, 10))
        #logger.info(master.execute(1, cst.READ_DISCRETE_INPUTS, 0, 8))
        #logger.info(master.execute(1, cst.READ_INPUT_REGISTERS, 100, 3))
        #logger.info(master.execute(1, cst.READ_HOLDING_REGISTERS, 100, 12))
        #logger.info(master.execute(1, cst.WRITE_SINGLE_COIL, 7, output_value=1))
        #logger.info(master.execute(1, cst.WRITE_SINGLE_REGISTER, 100, output_value=54))
        #logger.info(master.execute(1, cst.WRITE_MULTIPLE_COILS, 0, output_value=[1, 1, 0, 1, 1, 0, 1, 1]))
        #logger.info(master.execute(1, cst.WRITE_MULTIPLE_REGISTERS, 100, output_value=xrange(12)))

        # 读PLC线圈
        read1 = master.execute(4, cst.READ_COILS , 0, 1) #从PLC读Q0.0="请相机执行拍照"
        print('读取PLC的Q0.0：')
        print(read1)
            
        # 写保持寄存器DW0
        print('请求CCD处理结果：')
        write_i00 = master.execute(4, cst.WRITE_SINGLE_REGISTER , 42000, output_value=2) #往PLC写DW0=1、2   "请告诉我相机拍照结果 1为合格，2为不合格"


    except Exception as exc:
        print(str(exc))
        alarm = (str(exc))

    return read1,write_i00,alarm  ##如果异常就返回[],故障信息

if __name__ == "__main__":
    mod()

## 按键操作
import keyboard

while True:#making a loop
    try: #used try so that if user pressed other than the given key error will not be shown
        if keyboard.is_pressed('A'):#if key 'q' is pressed 
            print('You Pressed A Key!')
            break#finishing the loop
        else:
            pass
    except:
        break #if user pressed other than the given key the loop will breakc
